package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.android.uu.utils.uuUtils;
import com.hemaapp.BaseConfig;
import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.result.HemaArrayResult;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.BaseUtil;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.alipay.Result;
import com.hemaapp.yjnh.bean.Address;
import com.hemaapp.yjnh.bean.AlipayTrade;
import com.hemaapp.yjnh.bean.BlogDetail;
import com.hemaapp.yjnh.bean.Cart.ChildItem;
import com.hemaapp.yjnh.bean.ClientInfor;
import com.hemaapp.yjnh.bean.SubOrder;
import com.hemaapp.yjnh.bean.UnionTrade;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.bean.WeixinTrade;
import com.hemaapp.yjnh.listener.BuyConfirmView;
import com.hemaapp.yjnh.present.BuyConfirmPresent;
import com.hemaapp.yjnh.utils.ImageUtils;
import com.hemaapp.yjnh.view.BaseButtonDialog;
import com.hemaapp.yjnh.view.PayPasswordDialog;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;
import com.unionpay.uppay.PayActivity;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;

/**
 * 预约确认订单第二步
 *
 * @author GuiyouZhang
 * 2016.09.13
 */
public class BookConfirm2Activity extends BaseActivity implements OnClickListener, BuyConfirmView {

    private final static int REQUEST_INVOICE = 0x03;//发票信息

    @Bind(R.id.title_left_btn)
    ImageButton titleLeftBtn;
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_mobile)
    TextView tvMobile;
    @Bind(R.id.iv_goods)
    ImageView ivGoods;
    @Bind(R.id.tv_goods_name)
    TextView tvGoodsName;
    @Bind(R.id.tv_price)
    TextView tvPrice;
    @Bind(R.id.tv_count)
    TextView tvCount;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_blog_count)
    TextView tvBlogCount;
    @Bind(R.id.tv_total_fee)
    TextView tvTotalFee;
    @Bind(R.id.tv_coupons_info1)
    TextView tvCouponsInfo1;
    @Bind(R.id.tv_coupons_info2)
    TextView tvCouponsInfo2;
    @Bind(R.id.tv_coupons_info3)
    TextView tvCouponsInfo3;
    @Bind(R.id.ckbx_stamp)
    CheckBox ckbxStamp;
    @Bind(R.id.layout_food_stamp)
    LinearLayout layoutFoodStamp;
    @Bind(R.id.tv_invoice)
    TextView tvInvoice;
    @Bind(R.id.layout_invoice)
    LinearLayout layoutInvoice;
    @Bind(R.id.rbtn_friend)
    RadioButton rbtnFriend;
    @Bind(R.id.layout_friend)
    LinearLayout layoutFriend;
    @Bind(R.id.tv_balance)
    TextView tvBalance;
    @Bind(R.id.rbtn_balance)
    RadioButton rbtnBalance;
    @Bind(R.id.pay_balance_lay)
    LinearLayout payBalanceLay;
    @Bind(R.id.rbtn_alipay)
    RadioButton rbtnAlipay;
    @Bind(R.id.laytou_alipay)
    LinearLayout laytouAlipay;
    @Bind(R.id.rbtn_union)
    RadioButton rbtnUnion;
    @Bind(R.id.layout_unipay)
    LinearLayout layoutUnipay;
    @Bind(R.id.rbtn_wechat)
    RadioButton rbtnWechat;
    @Bind(R.id.layout_wechat)
    LinearLayout layoutWechat;
    @Bind(R.id.tv_submit)
    TextView tvSubmit;

    BuyConfirmPresent present;
    IWXAPI msgApi = WXAPIFactory.createWXAPI(this, null);//微信
    private ArrayList<RadioButton> rbtns = new ArrayList<RadioButton>();// 存储5中支付方式的RadioButton
    private BlogDetail mBlog;//某个规格的商品信息
    DecimalFormat df = new DecimalFormat("#0.00");//保留两位小数
    private String useCouponHint = "";//已用多少张粮票，还需支付多少现金的提示语。在切换是否使用粮票时使用

    //预约类信息
    private String mBookDate;//走走预约日期
    private String mBookName;//走走预约人姓名
    private String mBookMobile;//走走预约人联系方式
    //发票信息
    private int invoice_type = 3;//发票类型：1纸质发票，2电子发票，3无发票
    private String invoice_head = "";//发票抬头
    private String invoice_email = "无";//电子发票的邮箱地址
    private String invoice_content = "无";//发票内容

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_book_confirm_2);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        msgApi.registerApp(BaseConfig.APPID_WEIXIN);
        present = new BuyConfirmPresent(mContext, this, getApplicationContext().getUser(), "4");
        init();
    }

    @Override
    protected void onResume() {
        present.onWechatPayFinish();
        super.onResume();
    }

    private void init() {
        rbtns.add(rbtnAlipay);
        rbtns.add(rbtnUnion);
        rbtns.add(rbtnWechat);
        rbtns.add(rbtnBalance);
        rbtns.add(rbtnFriend);
        present.setBlog(mBlog);
        present.init();
    }

    @OnClick({R.id.title_left_btn, R.id.layout_food_stamp, R.id.layout_invoice,
            R.id.layout_friend, R.id.pay_balance_lay, R.id.laytou_alipay,
            R.id.layout_unipay, R.id.layout_wechat, R.id.tv_submit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_btn:
                finish();
                break;
            case R.id.layout_food_stamp:
                ckbxStamp.setChecked(!ckbxStamp.isChecked());
                break;
            case R.id.layout_invoice:
                Intent itInvoice = new Intent(mContext, InvoiceActivity.class);
                itInvoice.putExtra("type", invoice_type);
                itInvoice.putExtra("head", invoice_head);
                itInvoice.putExtra("email", invoice_email);
                itInvoice.putExtra("content", invoice_content);
                startActivityForResult(itInvoice, REQUEST_INVOICE);
                break;
            case R.id.layout_friend:
//                Intent itFriend = new Intent(mContext, FriendPayActivity.class);
//                itFriend.putExtra("name", mBlog.getName());
//                itFriend.putExtra("fee", df.format(present.getTotalFee()) + "");
//                User user = getApplicationContext().getUser();
//                itFriend.putExtra("info", user.getNickname() + "(" + user.getUsername() + ")");
//                startActivityForResult(itFriend, REQUEST_FRIEND);
                break;
            case R.id.pay_balance_lay:
                setRbtn(rbtnBalance);
                break;
            case R.id.laytou_alipay:
                setRbtn(rbtnAlipay);
                break;
            case R.id.layout_unipay:
                setRbtn(rbtnUnion);
                break;
            case R.id.layout_wechat:
                setRbtn(rbtnWechat);
                break;
            case R.id.tv_submit:
                present.submitOrder(mBookName, mBookMobile, mBookDate);
                break;
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        mBlog = (BlogDetail) mIntent.getSerializableExtra("blog");
        mBookDate = mIntent.getStringExtra("date");
        mBookName = mIntent.getStringExtra("name");
        mBookMobile = mIntent.getStringExtra("mobile");
    }

    @Override
    protected void setListener() {
        titleText.setText("确认订单");
        tvInvoice.setText("不开发票");
        //选择粮票
        ckbxStamp.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                double finalStamp = present.useFoodStamp(isChecked);
                if (isChecked) {
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append(finalStamp + "粮票，还需支付¥" + uuUtils.formatAfterDot2(present.getTotalFee()-finalStamp+""));
                } else {
                    tvCouponsInfo3.setText("您已使用");
                    BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
                    tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(present.getTotalFee()+""));
                }
            }
        });
    }

    private void setRbtn(RadioButton rbtn) {
        for (RadioButton rb : rbtns) {
            if (rbtn.equals(rb)) {
                rb.setChecked(true);
            } else {
                rb.setChecked(false);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_INVOICE:
                invoice_type = data.getIntExtra("type", 3);
                invoice_head = data.getStringExtra("head");
                invoice_email = data.getStringExtra("email");
                invoice_content = data.getStringExtra("content");
                String info = "";
                if (invoice_type == 1) {
                    info = "纸质发票\n" + invoice_head + "\n" + invoice_content;
                } else if (invoice_type == 2) {
                    info = "电子发票\n" + invoice_head + "\n" + invoice_content;
                } else {
                    info = "不开发票";
                }
                tvInvoice.setText(info);
                present.setInvoiceInfo(invoice_type, invoice_head, invoice_email, invoice_content);
                break;
            default:
                //银联的支付回调
                present.onUniPayFinish(data);
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void beforeLoading() {
        showProgressDialog("请稍候");
    }

    @Override
    public void loadingFinish() {
        cancelProgressDialog();
    }

    @Override
    public void setBlogs() {
        tvName.setText(mBookName);
        tvMobile.setText(mBookMobile);
        ImageUtils.loadSmalImage(mContext, mBlog.getImgurl(), ivGoods);
        tvGoodsName.setText(mBlog.getName());
        tvPrice.setText("¥"+uuUtils.formatAfterDot2(mBlog.getPrice()));
        int buycount = mIntent.getIntExtra("buycount", 1);
        tvCount.setText("x"+buycount);
        tvDate.setText(mBookDate);
        tvBlogCount.setText("共" + buycount + "件商品");
        double price = Double.parseDouble(mBlog.getPrice());
        double score = Double.parseDouble(mBlog.getScore());
        double needScores = buycount * score;
        present.setBuyCount(buycount);
        present.setNeedScores(needScores);
        tvCouponsInfo1.setText("可使用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo1, R.drawable.food_stamp_grey);
        tvCouponsInfo1.append(df.format(needScores)+"粮票");
    }

    @Override
    public void setAddress(Address address) {

    }

    @Override
    public void setClientInfo(double balance, double score) {
        tvBalance.setText("（可用 ¥" + df.format(balance) + ")");
        tvCouponsInfo2.setText("该商品可用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
        tvCouponsInfo2.append(present.getNeedCoupons() + "粮票 (可用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo2, R.drawable.food_stamp_black);
        tvCouponsInfo2.append(df.format(score)+"粮票)");
    }

    @Override
    public void setFreight(String freight) {

    }

    @Override
    public void setTotalFee(String totalFee) {
        tvTotalFee.setText("¥" + totalFee);
        tvCouponsInfo3.setText("您已使用");
        BaseUtil.addStampSign(mContext, tvCouponsInfo3, R.drawable.food_stamp_grey);
        tvCouponsInfo3.append("0.00粮票，还需支付¥"+uuUtils.formatAfterDot2(totalFee));
    }

    @Override
    public void toNextPage(String orderId) {
        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                finish();
            }
        }, 1000);
    }

    @Override
    public int getPayment() {
        if (rbtnAlipay.isChecked()) {
            return 1;
        }
        if (rbtnUnion.isChecked()) {
            return 2;
        }
        if (rbtnWechat.isChecked()) {
            return 3;
        }
        if (rbtnBalance.isChecked()) {
            return 4;
        }
        if (rbtnFriend.isChecked()) {
            return 5;
        }
        return -1;//没有选择支付方式：可能是全粮票
    }

    @Override
    public void showPayPwdDialog(PayPasswordDialog.onPasswordClickListener listener) {
        PayPasswordDialog dialog = new PayPasswordDialog(mContext);
        dialog.setClickListener(listener);
        dialog.builder().show();
    }

    @Override
    public void showAlertDialog(String title, String ok, BaseButtonDialog.OnButtonListener listener) {
        BaseButtonDialog dialog = new BaseButtonDialog(mContext);
        dialog.setText(title);
        dialog.setRightButtonText(ok);
        dialog.setButtonListener(listener);
        dialog.setCancelable(true);
        dialog.show();
    }
}
